package com.unibeta.cloudtest.mesher.modules.discovery.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.unibeta.cloudtest.mesher.config.ConfigurationProxy;
import com.unibeta.cloudtest.mesher.modules.discovery.EndpointsDiscovery;
import com.unibeta.cloudtest.mesher.modules.discovery.bean.EndpointInstance;

@Service
public class NacosEndpointsDiscoveryImpl implements EndpointsDiscovery {

	@Override
	public List<EndpointInstance> list(String serviceName) throws Exception {
		return this.list(ConfigurationProxy.getProperty(CLOUDTEST_MESH_REGISTRY_SERVER_HOST), serviceName);
	}

	@Override
	public List<EndpointInstance> list(String registryHost, String serviceName) throws Exception {

		List<EndpointInstance> list = new ArrayList<EndpointInstance>();

//		Unirest.setTimeouts(0, 0);
		HttpResponse<String> response = Unirest
				.get(registryHost + "/nacos/v1/ns/instance/list?serviceName=" + serviceName).asString();

		Map body = JSONObject.parseObject(response.getBody(), Map.class);

		if (null != body) {

			List<Map> hosts = (List) body.get("hosts");
			for (Map m : hosts) {
				boolean enabled = Boolean.valueOf(m.get("enabled").toString());
				boolean valid = Boolean.valueOf(m.get("valid").toString());
				boolean healthy = Boolean.valueOf(m.get("healthy").toString());

				if (enabled & valid & healthy) {
					EndpointInstance ei = new EndpointInstance();

					String ip = m.get("ip").toString();
					Integer port = Integer.valueOf(m.get("port").toString());
					String instanceId = m.get("instanceId").toString();

					ei.setEnabled(enabled);
					ei.setHealthy(healthy);
					ei.setInstanceId(instanceId);
					ei.setIp(ip);
					ei.setPort(port);
					ei.setServiceName(serviceName);
					ei.setValid(valid);

					list.add(ei);
				}
			}

		}
		return list;

	}

}
